package com.ruoyi.web.controller.system;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.RecordProp;
import com.ruoyi.system.domain.RecordTable;
import com.ruoyi.system.domain.SysTag;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.SysTagServiceImpl;
import com.ruoyi.web.controller.tool.ExcelUtilMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.UnknownHostException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 档案  Controller
 *
 * @author tangrs
 * @date 2022-10-09
 */
@RestController
@RequestMapping("/system/RecordManage")
public class RecordManageController extends BaseController {
    @Autowired
    private IRecordManageService recordManageService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IRecordPropService iRecordPropService;
    @Autowired
    private IRecordTableService iRecordTableService;
    @Autowired
    private SysTagServiceImpl sysTagService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${server.port}")
    private String port;


    /**
     * 查询档案  列表
     */
    @PreAuthorize("@ss.hasPermi('system:archives:list')")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody Map<String, Object> map) throws UnknownHostException {
        PageHelper.startPage((Integer) map.get("pageNum"), (Integer) map.get("pageSize"));
        List<Map<String, Object>> mapList = recordManageService.selectRecordManageList(map);
        for (Map<String, Object> stringObjectMap : mapList) {
            String path = "http://47.94.201.26:"+port;
            if (stringObjectMap.get("filePath") != null) {
                stringObjectMap.put("filePath", path + stringObjectMap.get("filePath").toString());
            }
            if (stringObjectMap.get("imagePath") != null) {
                stringObjectMap.put("imagePath", path + stringObjectMap.get("imagePath").toString());
            }
            //便利标签
            if (stringObjectMap.get("tag") != null) {
                Map<String, String> tag = Arrays.stream(stringObjectMap.get("tag").toString().split(",")).collect(Collectors.toMap(
                        s -> s.split(",")[0],
                        s -> s.split(",")[0]
                ));
                SysTag newTag = new SysTag();
                List<SysTag> list = sysTagService.getList(newTag);
                List<SysTag> collect = list.stream().filter(f -> tag.containsKey(f.getId().toString())).collect(Collectors.toList());
                StringBuilder stringBuilder = new StringBuilder();
                for (SysTag sysTag : collect) {
                    stringBuilder.append(sysTag.getLabel()).append(";");
                }
                if (stringBuilder.length() > 0) {
                    stringObjectMap.put("tag", stringBuilder.substring(0, stringBuilder.lastIndexOf(";")));
                }

            }
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 查询档案  馆藏
     */
    @PreAuthorize("@ss.hasPermi('system:archives:list')")
    @PostMapping("/listbook")
    public AjaxResult listFileBook(@RequestBody Map<String, Object> map) {
        PageHelper.startPage((Integer) map.get("pageNum"), (Integer) map.get("pageSize"));
        List<Map<String, Object>> mapList = recordManageService.selectRecordManageListBook(map);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 借阅记录档案查询  列表
     */
    @PreAuthorize("@ss.hasPermi('system:archives:list')")
    @PostMapping("/listBro")
    public AjaxResult listBro(@RequestBody Map<String, Object> map) {
        List<Map<String, Object>> mapList = null;
        String tbType = map.get("tbType").toString();
        String tbName = map.get("tbName").toString();
        String id = map.get("id").toString();
        String typeId = map.get("typeId").toString();
        if ("1".equals(tbType)) { // 借阅案卷信息，查询卷内信息
            // 获取卷内tbName名称
            // 封装archId和tbName值
            // 查询数据
            RecordTable recordTable = new RecordTable();
            recordTable.setTypeId(typeId);
            recordTable.setTbType("2");
            String tbNameNew = iRecordTableService.selectRecordTableList(recordTable).get(0).getTbName();
            Map<String, Object> mapFile = new HashMap<>();
            mapFile.put("tbName", tbNameNew);
            mapFile.put("archId", id);
            mapList = recordManageService.selectRecordManageList(mapFile);
        } else {
            Map<String, Object> mapArch = new HashMap<>();
            mapArch.put("tbName", tbName);
            mapArch.put("id", id);
            mapList = recordManageService.selectRecordManageList(mapArch);
        }
        return AjaxResult.success(mapList);
    }

    /**
     * 导出档案  列表
     */
    @PreAuthorize("@ss.hasPermi('system:archives:export')")
    @Log(title = "导出档案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody Map<String, Object> map) {
        // 导出表头
        RecordProp recordProp = new RecordProp();
        recordProp.setIsCustom(map.get("isCustom").toString());
        recordProp.setStatus(map.get("status").toString());
        recordProp.setTableId(Long.valueOf(map.get("tableId").toString()));
        List<RecordProp> propList = iRecordPropService.selectRecordPropList(recordProp);
        // 导出数据
        recordProp.setTbName(map.get("tbName").toString());
        List<Map<String, Object>> mapList = recordManageService.selectRecordManageList(map);
        // 导出工具
        ExcelUtilMap util = new ExcelUtilMap();
        util.exportExcelMap(response, mapList, "文件数据", propList);
    }

    /**
     * 导出档案  列表
     */
    @PreAuthorize("@ss.hasPermi('system:archives:export')")
    @Log(title = "导出档案", businessType = BusinessType.EXPORT)
    @PostMapping("/exportbook")
    public void exportbook(HttpServletResponse response, @RequestBody Map<String, Object> map) {
        // 导出表头
        List<RecordProp> propList = iRecordPropService.selectRecordPropListBook(map);
        map.remove("archTableId");
        map.remove("fileTableId");
        // 导出数据
        List<Map<String, Object>> mapList = recordManageService.selectRecordManageListBook(map);
        // 导出工具
        ExcelUtilMap util = new ExcelUtilMap();
        util.exportExcelMap(response, mapList, "文件数据", propList);
    }

    /**
     * 导入数据模板
     */
    @PreAuthorize("@ss.hasPermi('system:archives:importTemplate')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, @RequestBody Map<String, Object> map) {
        // 导出表头
        RecordProp recordProp = new RecordProp();
        recordProp.setIsCustom(map.get("isCustom").toString());
        recordProp.setStatus(map.get("status").toString());
        recordProp.setTableId(Long.valueOf(map.get("tableId").toString()));
        List<RecordProp> propList = iRecordPropService.selectRecordPropList(recordProp);
        // 导出工具
        ExcelUtilMap util = new ExcelUtilMap();
        util.exportExcelMap(response, null, "文件数据", propList);
    }

    /**
     * 文件导入
     */
    @PreAuthorize("@ss.hasPermi('system:archives:import')")
    @Log(title = "文件导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(MultipartFile file, String tbName, Long tableId, String isCustom, String tbType) throws Exception {
        RecordProp recordProp = new RecordProp();
        recordProp.setIsCustom(isCustom);
        recordProp.setTableId(tableId);
        List<RecordProp> propList = iRecordPropService.selectRecordPropList(recordProp);
        ExcelUtilMap util = new ExcelUtilMap();
        List<Map<String, Object>> mapList = util.importExcelMap(file.getInputStream(), propList);
        recordProp.setTbName(tbName);
        String message = recordManageService.importFile(mapList, tbName, tbType);
        return AjaxResult.success(message);
    }

    /**
     * 根据ID获取档案
     */
    @PreAuthorize("@ss.hasPermi('system:archives:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id, String tbName) {
        return AjaxResult.success(recordManageService.selectRecordManageById(id, tbName));
    }

    /**
     * 新增档案
     */
    @PreAuthorize("@ss.hasPermi('system:archives:add')")
    @Log(title = "新增档案", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Map<String, Object> map) {
        return toAjax(recordManageService.insertRecordManage(map));
    }

    /**
     * 修改档案
     */
    @PreAuthorize("@ss.hasPermi('system:archives:edit')")
    @Log(title = "修改档案", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Map<String, Object> map) {
        return toAjax(recordManageService.updateRecordManage(map));
    }

    /**
     * 批量删除档案
     */
    @PreAuthorize("@ss.hasPermi('system:archives:remove')")
    @Log(title = "批量删除档案", businessType = BusinessType.DELETE)
    @PutMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids, String tbName) {
        return toAjax(recordManageService.deleteRecordManageByIds(ids, tbName));
    }

    /**
     * 批量文件上传
     */
    @PreAuthorize("@ss.hasPermi('system:archives:upload')")
    @Log(title = "批量文件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/multFile")
    public AjaxResult multFile(@RequestBody Map<String, Object> map) {
        String message = recordManageService.upLoadMultFile(map);
        return AjaxResult.success(message);
    }

    /**
     * 案卷归档申请
     */
    @PreAuthorize("@ss.hasPermi('system:archives:apply')")
    @Log(title = "案卷归档申请", businessType = BusinessType.UPDATE)
    @PutMapping("/apply/{ids}")
    public AjaxResult updateArchivesApply(@PathVariable String[] ids, String tbName, String tbType) {
        return toAjax(recordManageService.updateArchivesApplyByIds(ids, tbName, tbType));
    }

    /**
     * 案卷归档审批通过
     */
    @PreAuthorize("@ss.hasPermi('system:archives:approve')")
    @Log(title = "案卷归档通过", businessType = BusinessType.UPDATE)
    @PutMapping("/approve/{ids}")
    public AjaxResult updateArchivesApprove(@PathVariable String[] ids, String tbName, String tbType) {
        return toAjax(recordManageService.updateArchivesApprove(ids, tbName, tbType));
    }

    /**
     * 案卷归档审批拒绝
     */
    @PreAuthorize("@ss.hasPermi('system:archives:reject')")
    @Log(title = "案卷归档拒绝", businessType = BusinessType.UPDATE)
    @PutMapping("/reject/{ids}")
    public AjaxResult updateArchivesReject(@PathVariable String[] ids, String tbName, String tbType) {
        return toAjax(recordManageService.updateArchivesReject(ids, tbName, tbType));
    }

    /**
     * 案卷包导出
     */
    @PreAuthorize("@ss.hasPermi('system:archives:export')")
    @Log(title = "案卷包导出", businessType = BusinessType.EXPORT)
    @PostMapping("/anJuanBaoExport/{id}")
    public void anJuanBaoExport(@PathVariable("id") String id, @RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        //生成文件并反回
        File resfile = recordManageService.selectRecordFileExport(id, map);
        if (ObjectUtil.isEmpty(resfile)) {
            return;
        }
        try {
            String downloadName = "案卷.zip";
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            // FileUtils.writeBytes(resfile.getAbsolutePath(), response.getOutputStream());
            FileUtil.writeToStream(resfile, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            resfile.delete();
        }

    }

    /**
     * 获取pdf相关参数
     */
    @PostMapping("/getPdfParam")
    public AjaxResult getPdfParam() {
        Map<String, Object> map = new HashMap<>();
        //pdf内容
        if (redisCache.getCacheObject("sys_config:pdf_shuiyin_cont") != null) {
            Object pdfShuiyinCont = redisCache.getCacheObject("sys_config:pdf_shuiyin_cont");
            map.put("pdfShuiyinCont", pdfShuiyinCont);
        }
        if (redisCache.getCacheObject("sys_config:pdf_shuiyin_isopen") != null) {
            //pdf开关
            Object pdfShuiyinIsopen = redisCache.getCacheObject("sys_config:pdf_shuiyin_isopen");
            map.put("pdfShuiyinIsopen", pdfShuiyinIsopen);
        }
        if (redisCache.getCacheObject("sys_config:dynamic_watermark") != null) {
            //动态水印 1用户名 2用户部门 3当天年月日
            Object dynamicWatermark = redisCache.getCacheObject("sys_config:dynamic_watermark");
            String[] split = dynamicWatermark.toString().split(",");
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                if (split[i].equals("1")) {
                    stringBuilder.append(SecurityUtils.getUsername()).append(",");
                } else if (split[i].equals("2")) {
                    SysUser user = SecurityUtils.getLoginUser().getUser();
                    SysDept dept = user.getDept();
                    stringBuilder.append(dept.getDeptName()).append(",");
                } else if (split[i].equals("3")) {
                    String dateToStr = DateUtils.parseDateToStr("yyyy-MM-dd", new Date());
                    stringBuilder.append(dateToStr).append(",");
                }
            }
            if (stringBuilder.length() > 0) {
                dynamicWatermark = stringBuilder.substring(0, stringBuilder.length() - 1);
            }
            map.put("dynamicWatermark", dynamicWatermark);
        }
        if (redisCache.getCacheObject("sys_config:img_watermark") != null) {
            //图片logo
            Object imgWatermark = redisCache.getCacheObject("sys_config:img_watermark");
            map.put("imgWatermark", imgWatermark);
        }
        //图片位置
        if (redisCache.getCacheObject("sys_config:imgWatermarkPos") != null) {
            //图片logo
            Object imgWatermarkPos = redisCache.getCacheObject("sys_config:imgWatermarkPos");
            map.put("imgWatermarkPos", imgWatermarkPos);
        }
        return AjaxResult.success(map);
    }


}
